package com.enation.app.shop.front.api.appcontroller;

import com.enation.app.base.core.model.Member;
import com.enation.app.base.core.service.IMemberManager;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.order.model.Order;
import com.enation.app.shop.core.order.model.OrderItem;
import com.enation.app.shop.core.order.service.IOrderManager;
import com.enation.app.shop.core.order.service.OrderStatus;
import com.enation.app.shop.front.api.credit.entity.CreditAccount;
import com.enation.app.shop.front.api.credit.service.ICreditAccountManager;
import com.enation.app.shop.front.api.creditrecord.ICreditRecordManager;
import com.enation.app.shop.front.api.creditrecord.entity.CreditRecord;
import com.enation.app.shop.front.api.inpolicy.entity.InPolicy;
import com.enation.app.shop.front.api.inpolicy.service.IInpolicyManager;
import com.enation.app.shop.front.api.jpush.entity.JPushContent;
import com.enation.app.shop.front.api.jpush.service.IJPushManager;
import com.enation.app.shop.front.api.payrecord.entity.PayRecord;
import com.enation.app.shop.front.api.payrecord.service.IPayRecordManager;
import com.enation.app.shop.front.api.random.IMobileRandomManager;
import com.enation.app.shop.front.api.random.entity.MoblieRandom;
import com.enation.app.shop.front.api.repayrecord.entity.RepayRecord;
import com.enation.app.shop.front.api.repayrecord.service.IRepayRecordManager;
import com.enation.app.shop.front.policyInsurance.entity.InsuranceCheck;
import com.enation.app.shop.front.policyInsurance.service.InsuranceCheckMapper;
import com.enation.framework.action.JsonResult;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.util.*;

/**
 *信用账户类
 */
@Scope("prototype")
@Controller
@RequestMapping("/app/creditaccount")
public class CreditAppAccountController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CreditAppAccountController.class);
    @Autowired
    private ICreditAccountManager creditAccountManager;
    @Autowired
    private IOrderManager orderManager;
    @Autowired
    private IGoodsManager goodsManager;
    @Autowired
    private IMobileRandomManager mobileRandomManager;
    @Autowired
    private ICreditRecordManager creditRecordManager;
    @Autowired
    private IRepayRecordManager repayRecordManager;
    @Autowired
    private IPayRecordManager payRecordManager;
    @Autowired
    private IInpolicyManager inpolicyManager;
    @Autowired
    private IMemberManager memberManager;
    @Autowired
    private IJPushManager jPushManager;
    @Autowired
    private InsuranceCheckMapper insuranceCheckMapper;


    /**
     *  //通过userid得到信用账户信息
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getaccountbyuserid")
    public JsonResult getAccountByUser(int userid){
        CreditAccount creditAccount=creditAccountManager.getCreditByUserId(userid);
        if (creditAccount==null){
            String a="{isactive:false,credit:600,fixed_amount:3000}";
            Map map=new HashMap();
            map.put("isactive",false);
            map.put("fixed_amount",3000);
            map.put("credit",600);
            map.put("total_quota",0.0);
            map.put("balance",0.0);
            map.put("provisional_maturity",0.0);
            map.put("provisional_quota_max",0.0);
            map.put("credit_id",0.0);
            return    JsonResultUtil.getObjectMessageJson(map,"没有信用账户信息");
        }
        Map map=new HashMap();
        map.put("isactive",true);
        map.put("fixed_amount",creditAccount.getFixed_amount());
        map.put("credit",600);
        CreditRecord creditRecord=creditRecordManager.getByUserIdAndRecetTime(userid);
        try {
            BigDecimal totalquota=creditRecord.getUpdate_credit();
            map.put("total_quota",totalquota);//
        }catch (Exception e){
            map.put("total_quota",3000);//
        }
        map.put("balance",creditAccount.getFixed_balance().add(creditAccount.getProvisional_quota_balance()));
        map.put("provisional_maturity",1);
        map.put("provisional_quota_max",10000);
        // map.put("provisional_maturity",creditAccount.getProvisional_maturity());
        map.put("credit_id",creditAccount.getCredit_id());
        return    JsonResultUtil.getObjectMessageJson(map,"获取信用账户信息");
    }

    /**
     *    //激活信用额度
     * @param userid
     * @param paypassword
     * @param fixedbalance
     * @return
     */
    @ResponseBody
    @RequestMapping("/openaccount")
    @Transactional
    public JsonResult openAccount(int userid,
                                  String paypassword,
                                  double fixedbalance){
        CreditAccount creditAccount=creditAccountManager.getCreditByUserId(userid);
        if (creditAccount==null){
            CreditAccount creditAccount1=new CreditAccount();
            creditAccount1.setUser_id(userid);
            BigDecimal fixamount=new BigDecimal("3000.00");//固定额度
            BigDecimal fixedbalancetemp=new BigDecimal(fixedbalance);//固定额度余额
            BigDecimal quota=new BigDecimal("7000.00");//临时额度
            BigDecimal quota_balance=new BigDecimal("0.00");//临时额度余额
            creditAccount1.setFixed_amount(fixamount);
            creditAccount1.setFixed_balance(fixedbalancetemp);
            creditAccount1.setCredit("600");//信用
            creditAccount1.setProvisional_quota_balance(quota_balance);//临时额度余额
            creditAccount1.setIsactive(1);
            creditAccount1.setProvisional_quota(quota);//临时额度
            // creditAccount1.setProvisional_maturity(3600*24*30L);//临时额度到期时间
            creditAccount1.setPayment_password(StringUtil.md5(paypassword));
            creditAccount1.setCerated_at(new Timestamp(System.currentTimeMillis()));
            creditAccount1.setUpdated_at(new Timestamp(System.currentTimeMillis()));
            int i=creditAccountManager.createCredit(creditAccount1);
            if (i>0){
                CreditRecord creditRecord=new CreditRecord();
                creditRecord.setCreate_at(new Timestamp(System.currentTimeMillis()));
                creditRecord.setDetail("信用账户激活成功");
                creditRecord.setUser_id(userid);
                creditRecord.setUpdate_credit(new BigDecimal(3000));
                creditRecordManager.createCreditRecord(creditRecord);
                PayRecord payRecord=new PayRecord();
                payRecord.setTime(new Timestamp(System.currentTimeMillis()));
                payRecord.setDetail("信用账户激活成功");
                payRecord.setUser_id(userid);
                payRecord.setPaymoney(new BigDecimal(3000));
                payRecordManager.Create(payRecord);
                CreditAccount creditAccount2=creditAccountManager.getCreditByUserId(userid);
                Member member=memberManager.getapp(userid);
                String jpushregisid=member.getJpushregisid();
                //jPush.JpushTest(userid,jpushregisid);
                jPushManager.JpushTest(userid,jpushregisid,1);
                return  getAccountByUser(creditAccount2.getUser_id());
            }else {
                return  JsonResultUtil.getErrorJson("激活信用额度失败");
            }
        }else {
            return  JsonResultUtil.getErrorJson("您已经有信用额度");
        }
    }

    /**
     * //忘记密码验证验证码
     * @param userid
     * @param randommobile
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequestMapping("/forgetPassword")
    public JsonResult forgetpassword(Integer userid,
                                     String randommobile,
                                     String mobile){
        MoblieRandom mobiletemp=mobileRandomManager.getByMobileRandom(randommobile,userid,mobile);
        if (mobiletemp==null){
            return JsonResultUtil.getErrorJson("验证码错误");
        }
        if (!mobiletemp.getRandom().equals(randommobile)){
            return JsonResultUtil.getErrorJson("验证码错误");
        }
        return JsonResultUtil.getSuccessJson("验证码正确");
    }

    /**
     * //忘记密码set验证码
     * @param userid
     * @param paypassword
     * @return
     */
    @ResponseBody
    @RequestMapping("/forgetPasswordSetPassword")
    public JsonResult forgetpasswordsetpassword(Integer userid,String paypassword){
        CreditAccount creditAccount=  creditAccountManager.getCreditByUserId(userid);
        if(creditAccount==null){
            return JsonResultUtil.getErrorJson("您还没有账户信息");
        }
        creditAccount.setPayment_password(StringUtil.md5(paypassword));
        try {
            creditAccountManager.updateCredit(creditAccount);
            return JsonResultUtil.getSuccessJson("设置密码成功");
        }catch (Exception e){
            System.out.println(e);
            return JsonResultUtil.getErrorJson("设置密码失败");
        }
    }


    /**
     * //调整额度
     * @param userid
     * @param upcredit
     * @param randommobile
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequestMapping("/upcredit")
    @Transactional
    public JsonResult updatecredit(Integer userid,
                                   BigDecimal upcredit,
                                   String randommobile,
                                   String mobile) {
        System.out.println(upcredit);
        MoblieRandom mobiletemp=mobileRandomManager.getByMobileRandom(randommobile,userid,mobile);
        if (mobiletemp==null){
            return JsonResultUtil.getErrorJson("验证码错误");
        }
        if (!mobiletemp.getRandom().equals(randommobile)){
            return JsonResultUtil.getErrorJson("验证码错误");
        }
        CreditAccount creditAccount= creditAccountManager.getCreditByUserId(userid);
        if (creditAccount==null){
            return JsonResultUtil.getErrorJson("您还没有激活信用账户");
        }else {
            CreditRecord creditRecord1=creditRecordManager.getByUserIdAndRecetTime(userid);
            BigDecimal totalquota=creditRecord1.getUpdate_credit();
            BigDecimal quabigDecimal=new BigDecimal(7000);//固定临时额度
            BigDecimal bigDecimal= upcredit.subtract(totalquota);//申请的临时额度
            creditAccount.setProvisional_quota_balance(creditAccount.getProvisional_quota_balance().add(bigDecimal));//临时额度余额
            creditAccount.setProvisional_quota(quabigDecimal.subtract(creditAccount.getProvisional_quota_balance()));//临时额度
            creditAccount.setApply_quota(new Timestamp(System.currentTimeMillis()));
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.MONTH, 1);
            creditAccount.setProvisional_maturity(new Timestamp(System.currentTimeMillis()));
            try {
                creditAccountManager.updateCredit(creditAccount);
                //信用账户记录
                CreditRecord creditRecord=new CreditRecord();
                creditRecord.setCreate_at( new Timestamp(System.currentTimeMillis()));
                creditRecord.setDetail("调整临时额度");
                creditRecord.setUser_id(userid);
                creditRecord.setUpdate_credit(upcredit);
                creditRecordManager.createCreditRecord(creditRecord);
                //支付记录
               PayRecord payRecord=new PayRecord();
               payRecord.setTime(new Timestamp(System.currentTimeMillis()));
               payRecord.setDetail("调整临时额度");
               payRecord.setUser_id(userid);
               payRecord.setPaymoney(upcredit);
               payRecordManager.Create(payRecord);
                return JsonResultUtil.getSuccessJson("调整额度成功");
            }catch (Exception e){
                LOGGER.error("调整额度失败", e);
                return JsonResultUtil.getErrorJson("调整额度失败");
            }

        }
    }


    /**
     * 商业险,饲料和兽药支付
     * @param orderid
     * @param userid
     * @param payment_id
     * @param payment_type
     * @param paypassword
     * @return
     */
    @RequestMapping("/paymentapp")
    @Transactional
    @ResponseBody
    public JsonResult payMentforapp(Integer orderid,
                                    Integer userid,
                                    Integer payment_id,//3货到付款   5信用额度
                                    String payment_type,
                                    String paypassword
    ){
        Order order=orderManager.get(orderid);
        List<Order> orders=orderManager.getByUserIdAndStatus(userid,null);
        if (orders==null){
            return JsonResultUtil.getErrorJson("您还没有订单信息");
        }
        if (order==null){
            return JsonResultUtil.getErrorJson("您还没有订单信息");
        }
        int i=0;
        if (order.getPay_status()==OrderStatus.ORDER_NOT_PAY){
            CreditAccount creditAccount=  creditAccountManager.getCreditByUserId(userid);
            String password=StringUtil.md5(paypassword);
            if (!creditAccount.getPayment_password().equals(password)){
                return JsonResultUtil.getErrorJson("支付密码错误");
            }
            if (creditAccount==null){
                return JsonResultUtil.getErrorJson("您还没有激活您的账户");
            }else {
                BigDecimal orderamount=new BigDecimal(order.getNeedPayMoney());
                BigDecimal balancefixed=creditAccount.getFixed_balance();//固定额度余额
                BigDecimal provisional_quota_balance=creditAccount.getProvisional_quota_balance();//临时额度余额
                BigDecimal balanceandquta=balancefixed.add(provisional_quota_balance);//现在可用余额
                if (balanceandquta.compareTo(orderamount)==-1){
                    return JsonResultUtil.getErrorJson("账户余额不足");
                }
                if (provisional_quota_balance.compareTo(orderamount)==-1){
                    BigDecimal a=orderamount.subtract(provisional_quota_balance);
                    BigDecimal bigDecimal=new BigDecimal(0.0);
                    creditAccount.setProvisional_quota_balance(bigDecimal);
                    creditAccount.setFixed_balance(balancefixed.subtract(a));
                }else {
                    creditAccount.setProvisional_quota_balance(provisional_quota_balance.subtract(orderamount));
                }
                creditAccount.setUpdated_at(new Timestamp(System.currentTimeMillis()));
                i=creditAccountManager.updateCredit(creditAccount);
            }
        }else {
            return JsonResultUtil.getErrorJson("您已经付过款了");
        }
        //消费统计
        List<OrderItem> orderItemList=orderManager.listGoodsItems(orderid);
        List<Integer> integers=new ArrayList<Integer>();
        for (OrderItem map:orderItemList){
            Integer goodsid=map.getGoods_id();
            Integer typeid=Integer.valueOf(goodsManager.get(goodsid).get("type_id").toString());
            double price= map.getNum()*map.getPrice();
            BigDecimal bigDecimal=new BigDecimal(price);
            PayRecord payRecord=new PayRecord();
            payRecord.setType_id(typeid);
            payRecord.setPaymoney(bigDecimal);
            payRecord.setOrderid(orderid);
            payRecord.setOrdersn(orderManager.get(orderid).getSn());
            payRecord.setUser_id(userid);
            payRecord.setTime(new Timestamp(System.currentTimeMillis()));
            payRecord.setDetail("商品购买");
            payRecordManager.Create(payRecord);
            integers.add(goodsid);
        }
//        //销量+1
//        for (Integer integer:integers){
//            Goods goods=goodsManager.getGoods(integer);
//            Integer buycount=goods.getBuy_count()+1;
//            goods.setBuy_count(buycount);
//            goodsManager.edit(goods);
//        }

        if (i==1){
            //会员积分
            Member member=memberManager.get(userid);
            try {
                //int point=Integer.valueOf(order.getNeedPayMoney().toString());
                Double d=order.getNeed_pay_money();
                int pon=d.intValue();
                int pointtemp=member.getPoint()+pon;
                int mptemp=member.getMp()+pon;
                member.setPoint(pointtemp);
                member.setMp(mptemp);
                memberManager.edit(member);
            }catch (Exception e){

            }
            //改变订单状态
            order.setStatus(OrderStatus.ORDER_PAY);
            order.setPay_status(OrderStatus.PAY_YES);
            order.setShip_status(OrderStatus.SHIP_NO);
            order.setPaymoney(order.getOrder_amount());
            order.setPayment_id(payment_id);
            order.setPayment_type(payment_type);
            try {
                orderManager.edit(order);
                List<OrderItem> orderItem=orderManager.listGoodsItems(orderid);
                for (OrderItem orderItem1:orderItem){
                    if (orderItem1.getUnit()!=null){
                        //保单出险日期
                        InPolicy warranty=inpolicyManager.warranty(orderItem1.getUnit());
                        Long begintime=new Date().getTime()+1000*60*60*24;//保单生效日期，购买成功24小时之后
                        if (warranty.getMonthnumber()==3) {
                            warranty.setBegin_time(new Timestamp(System.currentTimeMillis()));
                            warranty.setCase_date(new Timestamp(System.currentTimeMillis()));
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(new Date(begintime));
                            cal.add(Calendar.MONTH, 3);
                            warranty.setEnd_time(new Timestamp(cal.getTime().getTime()-1000*60*60*24));
                        } else if (warranty.getMonthnumber()==6) {
                            warranty.setBegin_time(new Timestamp(System.currentTimeMillis()));
                            warranty.setCase_date(new Timestamp(System.currentTimeMillis()));
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(new Date(begintime));
                            cal.add(Calendar.MONTH, 6);
                            warranty.setEnd_time(new Timestamp(cal.getTime().getTime()-1000*60*60*24));
                        } else if (warranty.getMonthnumber()==9) {
                            warranty.setBegin_time(new Timestamp(System.currentTimeMillis()));
                            warranty.setCase_date(new Timestamp(System.currentTimeMillis()));
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(new Date(begintime));
                            cal.add(Calendar.MONTH, 9);
                            warranty.setEnd_time(new Timestamp(cal.getTime().getTime()-1000*60*60*24));
                        } else {
                            warranty.setBegin_time(new Timestamp(System.currentTimeMillis()));
                            warranty.setCase_date(new Timestamp(System.currentTimeMillis()));
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(new Date(begintime));
                            cal.add(Calendar.MONTH, 12);
                            warranty.setEnd_time(new Timestamp(cal.getTime().getTime()-1000*60*60*24));
                        }
                        inpolicyManager.editwarranty(warranty);
                    }
                }
                return JsonResultUtil.getSuccessJson("支付成功");
            }catch (Exception e){
                LOGGER.error("支付失败", e);
                return JsonResultUtil.getErrorJson("支付失败");
            }
        }else {
            return JsonResultUtil.getSuccessJson("支付成功");
        }
    }




    /**
     * 政策保险支付
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping("/payforpolicyinsurance")
    public JsonResult payForZInsurance(Integer userid,
                                       Integer warrantyid,
                                       String payment_type,
                                       String paypassword){
        InPolicy inPolicy=inpolicyManager.getById(warrantyid);
        if (inPolicy==null){
            return JsonResultUtil.getErrorJson("支付错误");
        }
        if (inPolicy.getStatus()==4){//4：待支付 6：已承保
            CreditAccount creditAccount=creditAccountManager.getCreditByUserId(userid);
            String password=StringUtil.md5(paypassword);
            if (!creditAccount.getPayment_password().equals(password)){
                return JsonResultUtil.getErrorJson("支付密码错误");
            }
            if (creditAccount==null){
                return JsonResultUtil.getErrorJson("您还没有激活您的账户");
            }else {
                BigDecimal orderamount=inPolicy.getReal_money();
                BigDecimal balancefixed=creditAccount.getFixed_balance();//固定额度余额
                BigDecimal provisional_quota_balance=creditAccount.getProvisional_quota_balance();//临时额度余额
                BigDecimal balanceandquta=balancefixed.add(provisional_quota_balance);//现在可用余额
                if (balanceandquta.compareTo(orderamount)==-1){
                    return JsonResultUtil.getErrorJson("账户余额不足");
                }
                if (provisional_quota_balance.compareTo(orderamount)==-1){
                    BigDecimal a=orderamount.subtract(provisional_quota_balance);
                    BigDecimal bigDecimal=new BigDecimal(0.0);
                    creditAccount.setProvisional_quota_balance(bigDecimal);
                    creditAccount.setFixed_balance(balancefixed.subtract(a));
                }else {
                    creditAccount.setProvisional_quota_balance(provisional_quota_balance.subtract(orderamount));
                }
                creditAccount.setUpdated_at(new Timestamp(System.currentTimeMillis()));
                creditAccountManager.updateCredit(creditAccount);
                InsuranceCheck insuranceCheck=insuranceCheckMapper.selectByWarrantyId(warrantyid);
                Calendar cal=Calendar.getInstance();
                cal.setTime(insuranceCheck.getAuditor_date());
                Timestamp time=new Timestamp(System.currentTimeMillis());
                if(time.after(cal.getTime())){
                    Calendar cal1=Calendar.getInstance();
                    inPolicy.setBegin_time(insuranceCheck.getAuditor_date());
                    cal1.setTime(inPolicy.getBegin_time());
                    cal1.add(Calendar.MONTH, 12);
                    inPolicy.setEnd_time(new Timestamp(cal1.getTime().getTime()-1000*60*60*24));
                }else{
                    Calendar cal2=Calendar.getInstance();
                    inPolicy.setBegin_time(time);
                    cal2.setTime(inPolicy.getBegin_time());
                    cal2.add(Calendar.MONTH, 12);
                    inPolicy.setEnd_time(new Timestamp(cal2.getTime().getTime()-1000*60*60*24));
                }
                inPolicy.setPayment_type(payment_type);
                inpolicyManager.editwarranty(inPolicy);
                return JsonResultUtil.getSuccessJson("支付成功");
            }
        }else {
            return JsonResultUtil.getErrorJson("支付失败");
        }
    };

    /**
     * //修改信用账户密码
     * @param newpaypassword
     * @param repaypasswd
     * @param oldPayPassword
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/updatepaypassword")
    public JsonResult updatePayPassword(String newpaypassword, String repaypasswd, String oldPayPassword, int userid){
        CreditAccount creditAccount=creditAccountManager.getCreditByUserId(userid);
        oldPayPassword = oldPayPassword == null ? "" : StringUtil.md5(oldPayPassword);
        if (oldPayPassword.equals(creditAccount.getPayment_password()) ){
            String paypassword = newpaypassword;
            String paypasswd_re = repaypasswd;
            if(StringUtil.isEmpty(paypassword)){
                return JsonResultUtil.getErrorJson("新密码不能为空");

            }
            if(oldPayPassword.equals(StringUtil.md5(newpaypassword))){

                return JsonResultUtil.getErrorJson("您输入新旧密相同，请重新输入");
            }
            if (paypasswd_re.equals(paypassword)) {
                try {
                    creditAccountManager.updatepayPassword(paypassword,userid);
                    return JsonResultUtil.getSuccessJson("修改密码成功");

                } catch (Exception e) {
                    LOGGER.error("修改密码失败", e);
                    return JsonResultUtil.getErrorJson("修改密码失败");
                }
            } else {
                return JsonResultUtil.getErrorJson("修改失败！两次输入的密码不一致");

            }
        } else {
            return JsonResultUtil.getErrorJson("修改失败！原始密码不符");
        }
    }

    /**
     * //验证支付密码
     * @param paypassword
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkpaypassword")
    public JsonResult getpaypassword(String paypassword,Integer userid){
        CreditAccount creditAccount=creditAccountManager.getCreditByUserId(userid);
        if (creditAccount.getPayment_password().equals(StringUtil.md5(paypassword))){
            return JsonResultUtil.getSuccessJson("支付密码验证成功");
        }else{
            return JsonResultUtil.getErrorJson("支付密码验证失败");
        }
    }

    /**
     * //模拟验证码ios
     * @param mobile
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/mobileRandomios")
    public JsonResult getRandNumios(String mobile,Integer userid) {
        if (mobile.length()!=11){
            return JsonResultUtil.getErrorJson("请输入十一位手机号");
        }
        String charValue = "";
        for (int i = 0; i < 6; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        MoblieRandom moblieRandom=new MoblieRandom();
        moblieRandom.setRandom(charValue);
        moblieRandom.setUserid(userid);
        moblieRandom.setMobile(mobile);
        mobileRandomManager.creatMobileRandom(moblieRandom);
        System.out.println(charValue);
        return JsonResultUtil.getObjectMessageJson(charValue,"验证码");
    }

    /**
     * //模拟验证码andriod
     * @param mobile
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/mobileRandom")
    public JsonResult getRandNumandior(String mobile,Integer userid) {
        if (mobile.length()!=11){
            return JsonResultUtil.getErrorJson("请输入十一位手机号");
        }
        String charValue = "";
        for (int i = 0; i < 6; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        MoblieRandom moblieRandom=new MoblieRandom();
        moblieRandom.setRandom(charValue);
        moblieRandom.setUserid(userid);
        moblieRandom.setMobile(mobile);
        mobileRandomManager.creatMobileRandom(moblieRandom);
        System.out.println(charValue);
        return JsonResultUtil.getObjectMessageJson(charValue,"验证码");
    }

    public int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }

    /**
     * //额度记录
     * @param userid
     * @param year
     * @param month
     * @return
     */
    @ResponseBody
    @RequestMapping("/getRecordByTime")
    public JsonResult getRecordListByTime(Integer userid,String year,String month){
        List<CreditRecord> creditRecords=   creditRecordManager.getByUserIdAndYearMonth(userid,year,month);
        if (creditRecords==null){
            return JsonResultUtil.getErrorJson("没有记录");
        }else {
            List list=new ArrayList();
            for (CreditRecord creditRecord:creditRecords){
                Map map=new HashMap();
                map.put("record_id",creditRecord.getRecord_id());
                map.put("update_credit",creditRecord.getUpdate_credit());
                map.put("detail",creditRecord.getDetail());
                map.put("create_at",creditRecord.getCreate_at());
                list.add(map);
            }
            return JsonResultUtil.getObjectMessageJson(list,"临时额度记录");
        }
    }


    /**
     * //还款记录
     * @param userid
     * @param year
     * @param month
     * @return
     */
    @ResponseBody
    @RequestMapping("/getRepayRecordByTime")
    public JsonResult getRepayRecord(Integer userid,String year,String month){
        List<RepayRecord> RepayRecords=repayRecordManager.getByUserIdAndYearMonth(userid,year,month);
        if (RepayRecords==null){
            return JsonResultUtil.getErrorJson("没有记录");
        }else {
            List list=new ArrayList();
            for (RepayRecord repayRecord:RepayRecords){
                Map map=new HashMap();
                map.put("record_id",repayRecord.getRecord_id());
                map.put("update_credit",repayRecord.getUpdate_apply());
                map.put("detail",repayRecord.getDetail());
                map.put("create_at",repayRecord.getCreate_at());
                map.put("type",repayRecord.getType());//1:支付宝 2:微信
                list.add(map);
            }
            return JsonResultUtil.getObjectMessageJson(list,"还款记录");
        }
    }


    /**
     * //消费统计饼状图
     * @param userid
     * @param year
     * @param month
     * @return
     */
    @ResponseBody
    @RequestMapping("/getMoneyPayRecordCat")
    public JsonResult  getPayMoney(Integer userid,Integer year,Integer month){
        double at=0.0;//total
        double a1=0.0;//insrance
        double a2=0.0;//feed
        double a3=0.0;//drugs
        List<PayRecord> payRecords=payRecordManager.getByUserAndType(userid,year,month);
        if (payRecords==null){
            return JsonResultUtil.getErrorJson("您还没有消费");
        }
        for (PayRecord payRecord:payRecords){
            at+=payRecord.getPaymoney().doubleValue();
            if (payRecord.getType_id()==null){
                continue;
            }
            if (payRecord.getType_id()==64){
                a1+=payRecord.getPaymoney().doubleValue();
            }else if (payRecord.getType_id()==65){
                a2+=payRecord.getPaymoney().doubleValue();
            }else {
                a3+=payRecord.getPaymoney().doubleValue();
            }
        }
        NumberFormat num = NumberFormat.getPercentInstance();
        List<Map<String,Object>> list=new ArrayList();
        Map map1=new HashMap();
        Map map2=new HashMap();
        Map map3=new HashMap();
        if (at==0.0){
            map1.put("lable","保险");
            map1.put("value",0.0);
            map2.put("lable","饲料");
            map2.put("value",0.0);
            map3.put("lable","兽药");
            map3.put("value",0.0);
        }else {
            map1.put("lable","保险");
            map1.put("value",a1*100/at);
            map2.put("lable","饲料");
            map2.put("value",a2*100/at);
            map3.put("lable","兽药");
            map3.put("value",a3*100/at);
        }
        list.add(map1);
        list.add(map2);
        list.add(map3);
        return JsonResultUtil.getObjectMessageJson(list,"消费统计下面的图");
    }

    /**
     * //消费统计折线图
     * @param userid
     * @param year
     * @return
     */
    @ResponseBody
    @RequestMapping("/getMoneyPayRecord")
    public JsonResult  getPayMoneyRecord(Integer userid,Integer year){
    //    double paymoney=0.0;//total
        Integer month=0;
        List list=new ArrayList();
        while (month<12){
            double paymoney=0.0;//total
            Map map=new HashMap();
            month=month+1;
            List<PayRecord> payRecords=payRecordManager.getByUserAndType(userid,year,month);
            if (payRecords==null){
                return JsonResultUtil.getErrorJson("您还没有消费");
            }
            for (PayRecord payRecord:payRecords){
                paymoney+=payRecord.getPaymoney().doubleValue();
            }
            map.put("month",month);
            map.put("paymoney",paymoney);
            list.add(map);
        }
        return JsonResultUtil.getObjectMessageJson(list,"消费统计上面的图");
    }

    /**
     * //账单
     * @param userid
     * @param year
     * @param month
     * @return
     */
    @ResponseBody
    @RequestMapping("/getbill")
    public JsonResult getBill(Integer userid,Integer year,Integer month){
      List<PayRecord> payRecords=payRecordManager.getByUserAndTypeBill(userid,year,month);
      if (payRecords==null){
          return JsonResultUtil.getErrorJson("您还没有消费");
      }
      List list=new ArrayList();
      for (PayRecord payRecord:payRecords){
          Map map=new HashMap();
          map.put("time",payRecord.getTime());
          if (payRecord.getDetail()==null){
              map.put("money",payRecord.getPaymoney());
          }else {
              if (payRecord.getDetail().equals("商品购买")){
                  map.put("money","-"+payRecord.getPaymoney());
              }else if (payRecord.getDetail().equals("商品退款")){
                  map.put("money","+"+payRecord.getPaymoney());
              }else {
                  map.put("money","+"+payRecord.getPaymoney());
              }
          }
          map.put("orderid",payRecord.getOrderid());
          map.put("ordersn",payRecord.getOrdersn());
          map.put("detail",payRecord.getDetail());
          list.add(map);
      }
      return JsonResultUtil.getObjectMessageJson(list,"本月消费记录");
    }


    /**
     * //消息列表
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("getmessagebyuser")
    public JsonResult getmesssageByuser(Integer userid){
        List<JPushContent> jPushContents=jPushManager.getByUserid(userid);
        if (jPushContents==null){
            return JsonResultUtil.getErrorJson("您还没有消息");
        }else {
            return JsonResultUtil.getObjectMessageJson(jPushContents,"消息列表");
        }
    }

}
